package com.sap.mall.order.config;

import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import feign.RequestInterceptor;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Configuration
public class FeignConfig {

    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor() {
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate template) {
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if (attributes != null){
                    HttpServletRequest request = attributes.getRequest(); //
                    if (request != null) {
//                        log.info("RequestInceptor线程" + Thread.currentThread().getId());
                        // 同步请求头数据，主要是cookie
                        String cookie = request.getHeader("Cookie");
                        template.header("Cookie", cookie);
//                        log.info("feign远程之前先进行");
                    }
                }
            }
        };
    }
}
